/**
 * 信访台账列表页面JavaScript
 */

// 简单的通知服务
const NotificationService = {
    success: function(message) {
        console.log('成功:', message);
        // 可以在这里添加更多的通知显示逻辑
    },
    error: function(message) {
        console.error('错误:', message);
        alert('错误: ' + message);
    },
    warning: function(message) {
        console.warn('警告:', message);
        alert('警告: ' + message);
    },
    info: function(message) {
        console.info('信息:', message);
    }
};

class PetitionLedgerList {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 10; // 默认显示10条
        this.totalPages = 1;
        this.searchParams = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadAnalysisTasks();
        this.loadList();
        this.loadStatistics();
    }

    bindEvents() {
        // 绑定搜索按钮点击（如果有明确的搜索按钮）
        const searchButton = document.querySelector('button[type="submit"]');
        if (searchButton) {
            searchButton.addEventListener('click', (e) => {
                e.preventDefault();
                this.handleSearch();
            });
        }

        // 绑定重置按钮
        const resetButton = document.getElementById('resetSearch');
        if (resetButton) {
            resetButton.addEventListener('click', () => {
                this.resetSearch();
            });
        }

        // 绑定刷新按钮
        const refreshButton = document.getElementById('refreshBtn');
        if (refreshButton) {
            refreshButton.addEventListener('click', () => {
                this.loadList();
                this.loadStatistics();
            });
        }

        // 绑定每页显示行数选择器
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            pageSizeSelect.addEventListener('change', (e) => {
                this.pageSize = parseInt(e.target.value);
                this.currentPage = 1; // 重置到第一页
                this.loadList();
            });
        }

        // 绑定输入框变化事件，实现自动搜索
        const inputs = document.querySelectorAll('#searchForm input, #searchForm select');
        inputs.forEach(input => {
            input.addEventListener('change', () => {
                this.handleSearch();
            });

            // 对于文本输入，添加延迟搜索
            if (input.type === 'text') {
                let searchTimeout;
                input.addEventListener('input', () => {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        this.handleSearch();
                    }, 500);
                });
            }
        });
    }

    async loadAnalysisTasks() {
        try {
            // 信访台账应该显示所有类型的分析任务，使用regional作为analysis_type
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=regional&option_type=tasks`);
            const result = await response.json();

            if (result && result.length > 0) {
                this.populateAnalysisTaskSelect(result);
            }
        } catch (error) {
            console.error('加载分析任务失败:', error);
        }
    }

    async loadStatistics() {
        try {
            const response = await fetch('/api/petition-ledger/statistics/summary');
            const result = await response.json();

            if (result.code === 200) {
                this.updateStatisticsCards(result.data);
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    updateStatisticsCards(data) {
        // 更新总信访数
        const totalPetitions = document.getElementById('totalPetitions');
        if (totalPetitions) {
            totalPetitions.textContent = data.total_records || 0;
        }

        // 更新地区分布数
        const regionCount = document.getElementById('regionCount');
        if (regionCount) {
            const regionCountValue = data.region_statistics ? data.region_statistics.length : 0;
            regionCount.textContent = regionCountValue;
        }

        // 更新重复信访数
        const duplicateCount = document.getElementById('duplicateCount');
        if (duplicateCount) {
            // 通过情感分析统计中的负面数量来估算重复信访
            const negativeCount = data.sentiment_statistics ?
                data.sentiment_statistics.find(s => s.sentiment_type === '负面')?.count || 0 : 0;
            duplicateCount.textContent = negativeCount;
        }

        // 更新本月新增数
        const monthlyCount = document.getElementById('monthlyCount');
        if (monthlyCount) {
            // 这里简化处理，显示总数的10%作为月新增
            monthlyCount.textContent = Math.ceil((data.total_records || 0) * 0.1);
        }
    }

    populateAnalysisTaskSelect(tasks) {
        const select = document.getElementById('analysisTask');
        if (!select) return;

        // 清空现有选项，保留"全部任务"选项
        select.innerHTML = '<option value="">全部任务</option>';

        // 添加任务选项
        tasks.forEach(task => {
            const option = document.createElement('option');
            option.value = task.value;

            // 使用API返回的label作为显示文本
            option.textContent = task.label;

            // 添加任务创建时间作为提示（如果有的话）
            if (task.created_at) {
                option.title = `创建时间: ${new Date(task.created_at).toLocaleString('zh-CN')}`;
            }

            select.appendChild(option);
        });
    }

    getTaskTypeText(taskType) {
        const typeMap = {
            'RegionalAnalysis': '区域分析',
            'ComplaintTypeAnalysis': '投诉类型分析',
            'SentimentAnalysis': '情感分析',
            'ComplianceAnalysis': '规范性分析',
            'DuplicateAnalysis': '重复分析'
        };

        // 支持多任务类型
        if (taskType && taskType.includes(',')) {
            return taskType.split(',').map(type => typeMap[type.trim()] || type).join(', ');
        }

        return typeMap[taskType] || taskType || '未知类型';
    }

    handleSearch() {
        const form = document.getElementById('searchForm');
        if (!form) return;

        const formData = new FormData(form);
        this.searchParams = {};

        // 收集表单数据并映射到API参数
        for (let [key, value] of formData.entries()) {
            if (value.trim() !== '') {
                switch(key) {
                    case 'task_id':
                        this.searchParams.task_id = parseInt(value.trim());
                        break;
                    case 'start_date':
                        this.searchParams.date_from = value.trim();
                        break;
                    case 'end_date':
                        this.searchParams.date_to = value.trim();
                        break;
                    case 'region':
                        this.searchParams.region = value.trim();
                        break;
                    case 'complaint_type':
                        this.searchParams.complaint_type = value.trim();
                        break;
                    case 'sentiment':
                        this.searchParams.sentiment_type = value.trim();
                        break;
                    case 'compliance_status':
                        this.searchParams.compliance_status = value.trim();
                        break;
                    case 'has_duplicates':
                        this.searchParams.has_duplicates = value.trim();
                        break;
                    case 'search_term':
                        // 搜索关键词映射到对应的API参数
                        const searchTerm = value.trim();
                        this.searchParams.petitioner_name = searchTerm;
                        this.searchParams.respondent_unit = searchTerm;
                        break;
                }
            }
        }

        // 更新任务筛选显示
        this.updateTaskFilterDisplay();

        // 重置页码
        this.currentPage = 1;
        this.loadList();
    }

    updateTaskFilterDisplay() {
        const taskSelect = document.getElementById('analysisTask');
        const taskInfo = document.getElementById('currentTaskInfo');
        const taskName = document.getElementById('currentTaskName');

        if (taskSelect && taskSelect.value && taskInfo && taskName) {
            const selectedOption = taskSelect.options[taskSelect.selectedIndex];
            if (selectedOption && selectedOption.value !== '') {
                taskName.textContent = selectedOption.textContent;
                taskInfo.classList.remove('hidden');
            } else {
                taskInfo.classList.add('hidden');
            }
        } else if (taskInfo) {
            taskInfo.classList.add('hidden');
        }
    }

    resetSearch() {
        // 重置表单
        const form = document.getElementById('searchForm');
        if (form) {
            form.reset();
        }

        // 清空搜索参数
        this.searchParams = {};
        this.currentPage = 1;
        this.loadList();
    }

    async loadList() {
        try {
            // 显示加载状态
            const tbody = document.getElementById('dataTableBody');
            if (tbody) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="12" class="px-6 py-8 text-center">
                            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
                            <p class="mt-2 text-slate-600">正在加载数据...</p>
                        </td>
                    </tr>
                `;
            }

            const params = {
                page: this.currentPage,
                page_size: this.pageSize,
                ...this.searchParams
            };

            // 清空URL参数，重新构建
            const cleanParams = {};
            Object.keys(params).forEach(key => {
                if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
                    cleanParams[key] = params[key];
                }
            });

            const queryString = new URLSearchParams(cleanParams).toString();
            const response = await fetch(`/api/petition-ledger/?${queryString}`);
            const result = await response.json();

            if (result.code === 200) {
                this.renderTable(result.data);
                this.renderPagination(result.pagination);

                // 更新URL参数（不刷新页面）
                const newUrl = new URL(window.location);
                newUrl.search = queryString;
                window.history.replaceState({}, '', newUrl);

            } else {
                this.showError('加载列表失败');
            }
        } catch (error) {
            console.error('加载列表失败:', error);
            this.showError('系统错误，请稍后重试');
        }
    }

    renderTable(data) {
        const tbody = document.getElementById('dataTableBody');
        tbody.innerHTML = '';

        if (data.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="11" class="px-6 py-4 text-center text-gray-500">
                        <i class="fas fa-inbox text-2xl mb-2"></i>
                        <p>暂无数据</p>
                    </td>
                </tr>
            `;
            return;
        }

        data.forEach(item => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">
                    ${item.petition_record_id || '-'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${item.petitioner_name || '-'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    <div class="max-w-xs truncate" title="${item.petition_content || '-'}">
                        ${item.petition_content || '-'}
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    <div class="flex items-center">
                        <i class="fas fa-map-marker-alt text-gray-400 mr-1"></i>
                        ${item.region || item.province || item.city || '-'}
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${this.getStatusClass(item.analysis_status)}">
                        ${this.getStatusText(item.analysis_status)}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${this.getSentimentTypeBadge(item.sentiment_type)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    <div class="max-w-xs truncate" title="${item.complaint_type || '-'}">
                        ${item.complaint_type || '-'}
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${this.getComplianceStatusBadge(item.compliance_status)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${this.getDuplicateStatusBadge(item.is_duplicate)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${this.formatDate(item.created_at)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2">
                        <button onclick="viewDetail(${item.id})" class="text-blue-600 hover:text-blue-900 transition-colors" title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${item.has_location ? `
                            <button onclick="viewLocation(${item.longitude}, ${item.latitude})" class="text-green-600 hover:text-green-900 transition-colors" title="查看位置">
                                <i class="fas fa-map-marker-alt"></i>
                            </button>
                        ` : ''}
                        <button onclick="exportRecord(${item.id})" class="text-purple-600 hover:text-purple-900 transition-colors" title="导出记录">
                            <i class="fas fa-download"></i>
                        </button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    renderPagination(pagination) {
        const { total, page, page_size, total_pages } = pagination;

        // 更新分页信息
        const startRecord = (page - 1) * page_size + 1;
        const endRecord = Math.min(page * page_size, total);

        document.getElementById('startRecord').textContent = startRecord;
        document.getElementById('endRecord').textContent = endRecord;
        document.getElementById('totalRecordsTable').textContent = total;

        // 更新每页显示行数选择器
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            pageSizeSelect.value = page_size;
        }

        // 更新移动端按钮状态
        const prevBtnMobile = document.getElementById('prevPageMobile');
        const nextBtnMobile = document.getElementById('nextPageMobile');

        if (prevBtnMobile) {
            prevBtnMobile.disabled = page <= 1;
            prevBtnMobile.className = page <= 1
                ? 'relative inline-flex items-center px-4 py-2 border border-slate-300 text-sm font-medium rounded-lg text-slate-300 bg-slate-50 cursor-not-allowed'
                : 'relative inline-flex items-center px-4 py-2 border border-slate-300 text-sm font-medium rounded-lg text-slate-700 bg-white hover:bg-slate-50';
        }

        if (nextBtnMobile) {
            nextBtnMobile.disabled = page >= total_pages;
            nextBtnMobile.className = page >= total_pages
                ? 'relative inline-flex items-center px-4 py-2 border border-slate-300 text-sm font-medium rounded-lg text-slate-300 bg-slate-50 cursor-not-allowed'
                : 'relative inline-flex items-center px-4 py-2 border border-slate-300 text-sm font-medium rounded-lg text-slate-700 bg-white hover:bg-slate-50';
        }

        // 渲染桌面端分页导航
        const paginationNav = document.getElementById('paginationControls');
        if (!paginationNav) return;

        paginationNav.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.innerHTML = '<span class="sr-only">上一页</span><i class="fas fa-chevron-left"></i>';
        prevBtn.className = page <= 1
            ? 'relative inline-flex items-center px-2 py-2 rounded-l-md border border-slate-300 bg-slate-50 text-slate-300 text-sm font-medium cursor-not-allowed'
            : 'relative inline-flex items-center px-2 py-2 rounded-l-md border border-slate-300 bg-white text-slate-500 text-sm font-medium hover:bg-slate-50';
        prevBtn.disabled = page <= 1;
        prevBtn.onclick = () => this.goToPage(page - 1);
        paginationNav.appendChild(prevBtn);

        // 页码按钮
        const startPage = Math.max(1, page - 2);
        const endPage = Math.min(total_pages, page + 2);

        if (startPage > 1) {
            const firstBtn = this.createPageButton(1, false);
            paginationNav.appendChild(firstBtn);

            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'relative inline-flex items-center px-4 py-2 text-sm font-medium text-slate-700 bg-white';
                ellipsis.textContent = '...';
                paginationNav.appendChild(ellipsis);
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = this.createPageButton(i, i === page);
            paginationNav.appendChild(pageBtn);
        }

        if (endPage < total_pages) {
            if (endPage < total_pages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'relative inline-flex items-center px-4 py-2 text-sm font-medium text-slate-700 bg-white';
                ellipsis.textContent = '...';
                paginationNav.appendChild(ellipsis);
            }

            const lastBtn = this.createPageButton(total_pages, false);
            paginationNav.appendChild(lastBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.innerHTML = '<span class="sr-only">下一页</span><i class="fas fa-chevron-right"></i>';
        nextBtn.className = page >= total_pages
            ? 'relative inline-flex items-center px-2 py-2 rounded-r-md border border-slate-300 bg-slate-50 text-slate-300 text-sm font-medium cursor-not-allowed'
            : 'relative inline-flex items-center px-2 py-2 rounded-r-md border border-slate-300 bg-white text-slate-500 text-sm font-medium hover:bg-slate-50';
        nextBtn.disabled = page >= total_pages;
        nextBtn.onclick = () => this.goToPage(page + 1);
        paginationNav.appendChild(nextBtn);

        // 保存分页信息
        this.totalPages = total_pages;
    }

    createPageButton(pageNum, isActive) {
        const button = document.createElement('button');
        button.textContent = pageNum;
        button.className = isActive
            ? 'relative inline-flex items-center px-4 py-2 border border-indigo-500 bg-indigo-50 text-indigo-600 text-sm font-medium'
            : 'bg-white border-slate-300 text-slate-500 hover:bg-slate-50 relative inline-flex items-center px-4 py-2 border text-sm font-medium';
        button.onclick = () => this.goToPage(pageNum);
        return button;
    }

    goToPage(page) {
        if (page >= 1 && page <= this.totalPages) {
            this.currentPage = page;
            this.loadList();
        }
    }

    getStatusClass(status) {
        const statusMap = {
            'completed': 'bg-green-100 text-green-800',
            'processing': 'bg-yellow-100 text-yellow-800',
            'pending': 'bg-gray-100 text-gray-800'
        };
        return statusMap[status] || 'bg-gray-100 text-gray-800';
    }

    getStatusText(status) {
        const statusMap = {
            'completed': '已完成',
            'processing': '处理中',
            'pending': '待处理'
        };
        return statusMap[status] || status || '未知';
    }

    getSentimentTypeBadge(sentimentType) {
        if (!sentimentType) return '-';

        const sentimentMap = {
            'positive': { text: '正面', class: 'bg-green-100 text-green-800' },
            'neutral': { text: '中性', class: 'bg-blue-100 text-blue-800' },
            'negative': { text: '负面', class: 'bg-red-100 text-red-800' }
        };

        const sentiment = sentimentMap[sentimentType] || { text: sentimentType, class: 'bg-gray-100 text-gray-800' };
        return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${sentiment.class}">${sentiment.text}</span>`;
    }

    formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    getComplianceStatusBadge(status) {
        if (!status) return '-';

        const statusMap = {
            '合规': { text: '合规', class: 'bg-green-100 text-green-800' },
            '不合规': { text: '不合规', class: 'bg-red-100 text-red-800' },
            '部分合规': { text: '部分合规', class: 'bg-yellow-100 text-yellow-800' }
        };

        const statusObj = statusMap[status] || { text: status, class: 'bg-gray-100 text-gray-800' };
        return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusObj.class}">${statusObj.text}</span>`;
    }

    getDuplicateStatusBadge(isDuplicate) {
        if (isDuplicate === undefined || isDuplicate === null) return '-';

        if (isDuplicate) {
            return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">
                <i class="fas fa-exclamation-triangle mr-1"></i>重复
            </span>`;
        } else {
            return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                <i class="fas fa-check mr-1"></i>正常
            </span>`;
        }
    }

    showError(message) {
        NotificationService.error(message);
        console.error('错误:', message);
    }
}

// 辅助函数
function viewDetail(recordId) {
    if (recordId) {
        // 跳转到详情页面
        window.location.href = `/web/petition-ledger/${recordId}`;
    } else {
        NotificationService.warning('无效的记录ID');
    }
}

function viewLocation(longitude, latitude) {
    if (longitude && latitude) {
        // 打开地图查看位置
        const url = `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}&zoom=15`;
        window.open(url, '_blank');
    } else {
        NotificationService.warning('暂无位置信息');
    }
}

async function exportRecord(recordId) {
    try {
        showLoading();

        const response = await fetch('/api/petition-ledger/export', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                record_id: recordId,
                export_format: 'excel'
            })
        });
        const result = await response.json();

        if (result.code === 200) {
            const downloadUrl = result.data.download_url;
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = `petition_record_${recordId}.xlsx`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            NotificationService.success('导出成功');
        } else {
            NotificationService.error('导出失败');
        }
    } catch (error) {
        console.error('导出失败:', error);
        NotificationService.error('导出失败：' + error.message);
    } finally {
        hideLoading();
    }
}

// 清除任务筛选
function clearTaskFilter() {
    const taskSelect = document.getElementById('analysisTask');
    const taskInfo = document.getElementById('currentTaskInfo');

    if (taskSelect) {
        taskSelect.value = '';
    }

    if (taskInfo) {
        taskInfo.classList.add('hidden');
    }

    // 重新加载数据
    if (window.petitionLedgerList) {
        window.petitionLedgerList.searchParams = {};
        window.petitionLedgerList.currentPage = 1;
        window.petitionLedgerList.loadList();
    }
}

// 页面加载完成后自动初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已经初始化
    if (!window.petitionLedgerList) {
        window.petitionLedgerList = new PetitionLedgerList();
    }
});